const { app,BrowserWindow,ipcMain,dialog } = require('electron');
const path = require("path");
const DataStore = require("./renderer/musicDataStore.js");
const myStore = new DataStore({'name':'music data'});
app.whenReady().then(()=>{
    const mainWindows = new AppWindow({});
    mainWindows.webContents.on('did-finish-load',()=>{
        mainWindows.send('getTracks',myStore.getTracks());
    })
    ipcMain.on('message',(event,argument)=>{
        event.sender.send('receive','hi tom!');
    });
    ipcMain.on('add-music-window',(event, argument) => {
        const subWin = new AppWindow({
            width:500,
            height:400,
            parent:mainWindows,
            modal: true,
        },"add");
    });
    ipcMain.on('open-music-file',(event, args) => {
        dialog.showOpenDialog({
            properties:['openFile','multiSelections'],
            filters:[
                [{name:'Music',extensions:['mp3']}]
            ]
        }).then((files)=>{
            if(files){
                event.sender.send('selected-file',files.filePaths);
            }
        })
    });
    ipcMain.on("add-tracks",(event,tracks)=>{
        // console.log(tracks);
        const updateTracks =  myStore.addTrack(tracks).getTracks();
        mainWindows.send('getTracks',updateTracks);
    });
    ipcMain.on('delete-track',(event,trackId)=>{
        const updateTracks = myStore.delTracks(trackId).getTracks();
        event.sender.send('getTracks',updateTracks);
    });
})
app.on("activate",()=>{
    if(BrowserWindow.getAllWindows().length == 0){
        const mainWindows = new AppWindow({});
    }
})
app.on("window-all-closed",()=>{
    if(process.platform != "drawin"){
        app.quit();
    }
})
class AppWindow extends BrowserWindow{
    constructor(config,fileName) {
        if(fileName == null) fileName = "index";
        let baseConfig = {
            width:800,
            height:600,
            webPreferences:{
                nodeIntegration:true,
                preload:path.join(__dirname,`renderer/${fileName}.js`)
            }
        }
        config = {...baseConfig,...config};
        super(config);
        this.loadFile(`./renderer/${fileName}.html`);
    }
}